package com.tensquare.user.interceptor;

import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @program: tensquare_parent
 * @description:
 * @author: tianshengfei
 * @create: 2019-12-08 19:10
 **/
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("经过了拦截器");
        String authorization = request.getHeader("Authorization");
        if(StringUtils.isNotBlank(authorization) && authorization.startsWith("Bearer ")){
            //如果包含有Authorization头信息，就解析得到令牌
            String token = authorization.substring(7);
            //验证令牌
            try {
                Claims claims = jwtUtil.parseJWT(token);
                String role = (String) claims.get("roles");
                if(role != null){
                    if (role.equals("admin")) {
                        request.setAttribute("claims_admin",token);
                    }
                    if ( role.equals("user")) {
                        request.setAttribute("claims_user", token);
                    }
                }

            } catch (Exception e) {
                throw new RuntimeException("令牌不正确!");
            }
        }
        return true;
    }
}
